package cn.ug.pay.web.controller;

import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.core.login.LoginHelper;
import cn.ug.pay.bean.AreaBalanceBean;
import cn.ug.pay.bean.AreaTransactionBean;
import cn.ug.pay.bean.BillBean;
import cn.ug.pay.bean.request.MemberAccountParamBean;
import cn.ug.pay.bean.response.MemberAccountBean;
import cn.ug.pay.bean.response.MemberAccountManageBean;
import cn.ug.pay.bean.status.PayDistributePrefix;
import cn.ug.pay.bean.type.BillType;
import cn.ug.pay.bean.type.TradeType;
import cn.ug.pay.mapper.entity.MemberAccount;
import cn.ug.pay.mapper.entity.PayFundsRecord;
import cn.ug.pay.service.MemberAccountService;
import cn.ug.pay.service.PayFundsRecordService;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.ExportExcelController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 银行卡基础服务
 * @author ywl
 * @date 2018/2/5
 */
@RestController
@RequestMapping("memberAccount")
public class MemberAccountController {

    @Resource
    private MemberAccountService memberAccountService;
    @Autowired
    private PayFundsRecordService payFundsRecordService;
    @Resource
    private Config config;

    @GetMapping(value = "/record/list")
    public SerializeObject<DataTable<PayFundsRecord>> listRecord(@RequestHeader String accessToken, Page page, String memberId, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        memberId = UF.toString(memberId);
        int total = payFundsRecordService.count(memberId, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<PayFundsRecord> list = payFundsRecordService.query(memberId, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<PayFundsRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<PayFundsRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<PayFundsRecord>()));
    }

    @GetMapping(value = "/record/export")
    public void exportData(HttpServletResponse response, String memberId, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        memberId = UF.toString(memberId);
        List<PayFundsRecord> list = payFundsRecordService.query(memberId, startDate, endDate, 0, 0);
        if(list != null && list.size() > 0){
            String[] columnNames = { "日期","资金总额（元）", "冻结资金（元）", "可用资金（元）", "收入金额（元）", "提现金额（元）"};
            String [] columns = {"addDate", "totalAmount", "freezeAmount", "usableAmount", "incomeAmount", "withdrawAmount"};
            String fileName = "资金账户表";
            ExportExcelController<PayFundsRecord> export = new ExportExcelController<PayFundsRecord>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    /**
     * 查询会员资金账户列表(后台)
     * @param accessToken	              登录成功后分配的Key
     * @param maParamBean               请求参数
     * @return			                  分页数据
     */
    @RequestMapping(value = "queryMemberAccountList" , method = GET)
    public SerializeObject<DataTable<MemberAccountManageBean>> queryBankCardList(@RequestHeader String accessToken, MemberAccountParamBean maParamBean) {
        if(maParamBean.getPageSize() <= 0) {
            maParamBean.setPageSize(config.getPageSize());
        }
        DataTable<MemberAccountManageBean> dataTable = memberAccountService.queryMemberAccountList(maParamBean);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 会员资金账户导出
     * @param response
     * @param maParamBean
     * @return
     */
    @RequestMapping(value = "queryMemberAccountList/export" , method = GET)
    public SerializeObject<DataTable<MemberAccountManageBean>> queryBankCardListExport(HttpServletResponse response, MemberAccountParamBean maParamBean) {
        maParamBean.setPageSize(Integer.MAX_VALUE);
        DataTable<MemberAccountManageBean> dataTable = memberAccountService.queryMemberAccountList(maParamBean);
        List<MemberAccountManageBean> list = dataTable.getDataList();
        if(list != null && list.size() > 0){
            String[] columnNames = {"序号","手机号", "用户姓名", "资金总额", "冻结资金", "可用资金","红包返现总额","创建时间"};
            String [] columns = {"index","mobile", "name", "fundAmount", "freezeAmount", "usableAmount", "couponAmount","addTimeString"};
            String fileName = "资金账户总表";
            ExportExcelController<MemberAccountManageBean> export = new ExportExcelController<MemberAccountManageBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }


    @RequestMapping(value = "/area/balance" , method = GET)
    public SerializeObject<List<AreaBalanceBean>> queryBalanceList(@RequestHeader String accessToken, Order order) {
        return new SerializeObject<>(ResultType.NORMAL, memberAccountService.listAreaBalance(order.getOrder(), order.getSort()));
    }

    @RequestMapping(value = "/area/transaction" , method = GET)
    public SerializeObject<List<AreaTransactionBean>> queryTransactionList() {
        return new SerializeObject<>(ResultType.NORMAL, memberAccountService.listAreaTransaction());
    }

    /**
     * 查询会员可用余额
     * @param accessToken
     * @return
     */
    @GetMapping(value = "queryUsableAmount")
    public SerializeObject queryUsableAmount(@RequestHeader String accessToken) {
        Map<String,String> map = new HashMap<String,String>();
        BigDecimal usableAmount = memberAccountService.queryUsableAmount();
        map.put("usableAmount",usableAmount.toString());
        return new SerializeObject(ResultType.NORMAL, map);
    }

    /**
     * 创建资金账户
     * @param memberId  会员Id
     * @return
     */
    @PostMapping(value = "create")
    public SerializeObject create(String memberId) {
        memberAccountService.create(memberId);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 邀请返现
     * @param memberId
     * @param amount
     * @param type 类型 根据TradeType获取
     * @return
     */
    @PostMapping(value = "inviteReturnCash")
    public SerializeObject inviteReturnCash(String memberId,BigDecimal amount, Integer type){
        String orderId = memberAccountService.inviteReturnCash(memberId, amount, type);
        return new SerializeObject(ResultType.NORMAL, orderId);
    }

    /**
     * 根据会员Id获取可用体验金
     * @param
     * @return
     */
    @GetMapping(value = "queryUsableGram")
    public SerializeObject queryUsableGram(@RequestHeader String accessToken){
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError<>("00000102");
        }
        MemberAccountBean entity = memberAccountService.findByMemberId(memberId);
        return new SerializeObject(ResultType.NORMAL, entity.getUsableGram());
    }

    /**
     * 根据会员Id获取资金账户信息
     * @param memberId
     * @return
     */
    @GetMapping(value = "findByMemberId")
    public SerializeObject<MemberAccountBean> findByMemberId(String memberId){
        MemberAccountBean entity = memberAccountService.findByMemberId(memberId);
        return new SerializeObject(ResultType.NORMAL, entity);
    }
    /**
     * 导出
     * @param maParamBean
     * @param response
     * @return
     */
    @RequestMapping(value = "export", method = GET)
    public SerializeObject export(MemberAccountParamBean maParamBean,HttpServletResponse response) {
        maParamBean.setPageNum(1);
        maParamBean.setPageSize(Integer.MAX_VALUE);
        DataTable<MemberAccountManageBean> dataTable = memberAccountService.queryMemberAccountList(maParamBean);

        String fileName = "体验金账户管理";
        String[] columnNames = {"序号", "手机号", "姓名", "累计获得体验金（克）", "当前可用体验金（克）", "累计已获得体验金奖励（克）", "折算金额（元）", "对应金豆（个)"};
        String[] columns = {"index", "mobile", "name", "totalGram", "usableGram", "totalIncomeGram", "convertAmount", "convertBean"};
        int index = 1;
        for (MemberAccountManageBean bean : dataTable.getDataList()) {
            bean.setIndex(index);
            index++;
        }
        ExportExcelController<MemberAccountManageBean> export = new ExportExcelController<>();
        export.exportExcel(fileName, fileName, columnNames, columns, dataTable.getDataList(), response, ExportExcelUtil.EXCEL_FILE_2003);
        return new SerializeObject(ResultType.NORMAL, dataTable);
    }

    /**
     * 奖励发放
     * @param memberId
     * @param amount
     * @param type
     * @return
     */
    @PostMapping(value = "awardGiveOut")
    public SerializeObject awardGiveOut(String memberId,BigDecimal amount, Integer type){
        String orderId = memberAccountService.awardGiveOut(memberId, amount, type);
        return new SerializeObject(ResultType.NORMAL, orderId);
    }


}
